package com.my.socket.nio.v4;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by ZhongGang
 * at 2018/6/29 16:33
 */
public class ReadTask implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadTask.class);

    private Selector acceptSelector;
    private Selector readSelector;
    private Selector writeSelector;

    public ReadTask(Selector acceptSelector, Selector readSelector, Selector writeSelector) {
        this.acceptSelector = acceptSelector;
        this.readSelector = readSelector;
        this.writeSelector = writeSelector;
    }

    @Override
    public void run() {
        try {
            while (true) {
                this.readSelector.select();

                Set<SelectionKey> selectionKeys = this.readSelector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    try {
                        SelectionKey selectionKey = iterator.next();
                        iterator.remove();

                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        socketChannel.configureBlocking(false);
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        StringBuilder messageBuilder = new StringBuilder();
                        int length = socketChannel.read(byteBuffer);
                        while (length > 0) {
                            byteBuffer.flip();
                            String message = new String(byteBuffer.array(), 0, length);
                            messageBuilder.append(message);
                            byteBuffer.clear();
                            length = socketChannel.read(byteBuffer);
                        }
                        LOGGER.info("read from socket {}: {}", socketChannel, messageBuilder.toString());
                        socketChannel.write(ByteBuffer.wrap(messageBuilder.toString().getBytes()));
                    } catch (Exception e) {
                        LOGGER.error("exception caught, the error is {}", e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", e.getMessage());
        }
    }
}
